package com.xiaoq.shop.repository.impl;

import com.xiaoq.shop.entity.ShopPayTypeEntity;
import com.xiaoq.shop.repository.IShopPayTypeRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by chenjh on 2017/11/30.
 */
@Repository
public class ShopPayTypeRepositoryImpl implements IShopPayTypeRepository {

    @Autowired
    private Datastore datastore;

    @Override
    public boolean save(ShopPayTypeEntity shopPayTypeEntity) {
        if(shopPayTypeEntity==null || StringUtils.isBlank(shopPayTypeEntity.getId())){
            return false;
        }
        datastore.save(shopPayTypeEntity);
        return true;
    }

    @Override
    public ShopPayTypeEntity getByCommon(ShopPayTypeEntity shopPayTypeEntity) {
        if(shopPayTypeEntity == null){
            return null;
        }
       Query<ShopPayTypeEntity> shopPayTypeQuery = datastore.createQuery(ShopPayTypeEntity.class);
        if(StringUtils.isNotBlank(shopPayTypeEntity.getId())){
            shopPayTypeQuery.filter("_id", shopPayTypeEntity.getId());
        }
        if(StringUtils.isNotBlank(shopPayTypeEntity.getShopId())){
            shopPayTypeQuery.filter("shopId", shopPayTypeEntity.getShopId());
        }
        if(StringUtils.isNotBlank(shopPayTypeEntity.getShopType())){
            shopPayTypeQuery.filter("shopType", shopPayTypeEntity.getShopType());
        }
        if(shopPayTypeEntity.getPayTest() != null){
            shopPayTypeQuery.filter("payTest", shopPayTypeEntity.getPayTest());
        }
        return shopPayTypeQuery.get();
    }

    @Override
    public boolean updateById(ShopPayTypeEntity shopPayTypeEntity) {
        if(shopPayTypeEntity==null || StringUtils.isBlank(shopPayTypeEntity.getShopId())){
            return false;
        }
        Query<ShopPayTypeEntity> shopPayTypeQuery = datastore.createQuery(ShopPayTypeEntity.class)
                .filter("shopId", shopPayTypeEntity.getShopId());
        UpdateOperations<ShopPayTypeEntity> ops = datastore.createUpdateOperations(ShopPayTypeEntity.class);
        ops.set("payMethods", shopPayTypeEntity.getPayMethods());
        datastore.update(shopPayTypeQuery, ops);
        return true;
    }
}
